using UnityEngine;
using System.Collections;

public enum UnitState {Move, Idle, Attack, Stop, Hold, Harvesting};

public abstract class Unit : MonoBehaviour 
{
	//Public variables
	public int maxHealth;
	public int currentHealth;
	public float speed;
	public UnitState startingState;
	public int height;
	public int width;
	public float visionRange;
	public float rotationSpeed;
	
	//Protected variables
	protected Vector3 targetPosition;
	protected UnitState currentState;
	protected bool selected;
	protected MeshRenderer selectionCircle;

	// Use this for initialization
	void Start () 
	{
		selected = false;
		selectionCircle = (MeshRenderer)transform.Find("SelectionCircle").GetComponent("MeshRenderer");
		selectionCircle.enabled = false;
		transform.tag = "Units";
		currentState = UnitState.Idle;
		
		Vector3 v = transform.position;
		RaycastHit hit;
		if(Physics.Raycast(v, Vector3.down, out hit, 5.0f))
		{
			v.y = hit.point.y + collider.bounds.extents.y;
		}
				
		transform.position = v;
		
		Game.Instance.AddUnit(this);
		
		gameObject.AddComponent<Rigidbody>();
		
		rigidbody.freezeRotation = true;
		rigidbody.useGravity = false;
		
		primitiveStart();
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(Input.GetKeyDown(KeyCode.A))
			Selected();
		
		primitiveUpdate();
	}
	
	void FixedUpdate()
	{
		if(currentState == UnitState.Move)
		{
			if(transform.position.Equals(targetPosition))
				currentState = UnitState.Idle;
			else
			{
				Vector3 v = Vector3.Lerp(transform.position, targetPosition, (Time.fixedDeltaTime * speed));
				
				RaycastHit hit;
				if(Physics.Raycast(v, Vector3.down, out hit, 5.0f))
				{
					v.y = hit.point.y + collider.bounds.extents.y+0.2f;
				}
				
				transform.position = v;
			}
		}
		
		primitiveFixedUpdate();
	}
	
	private void SetCurrentState(UnitState currentState)
	{
		this.currentState = currentState;
	}
	
	public void MoveTo(Vector3 targetPosition)
	{
		this.targetPosition = targetPosition;
		SetCurrentState(UnitState.Move);
	}
	
	public void Selected()
	{

		selected = true;
		selectionCircle.enabled = true;
	}
	
	public void Deselected()
	{
		selected = false;
		selectionCircle.enabled = false;
	}
	
	public bool GetSelected()
	{
		return selected;
	}
	
	public void setTag(string tag)
	{
		transform.tag = tag;
	}
	
	public void setVisionRange(float visionRange)
	{
		this.visionRange = visionRange;
	}
	
	protected abstract void primitiveUpdate();
	protected abstract void primitiveStart();
	protected abstract void primitiveFixedUpdate();
	
}
